package com.train.mgr.modules.biz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.train.common.exception.BizException;
import com.train.common.model.PageResult;
import com.train.common.utils.AuthUtils;
import com.train.mgr.modules.biz.dto.request.CourseStuGroupReqDTO;
import com.train.mgr.modules.biz.dto.request.GroupQueryDTO;
import com.train.mgr.modules.biz.dto.response.GroupRespListDTO;
import com.train.mgr.modules.biz.entity.CourseStuGroup;
import com.train.mgr.modules.biz.entity.CourseStuGroupRel;
import com.train.mgr.modules.biz.mapper.CourseStuGroupMapper;
import com.train.mgr.modules.biz.service.ICourseStuGroupRelService;
import com.train.mgr.modules.biz.service.ICourseStuGroupService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程学员分组表 服务实现类
 * </p>
 *
 * @author cxg
 * @date 2025-10-02
 */
@Slf4j
@RequiredArgsConstructor
@Service("ICourseStuGroupService")
public class CourseStuGroupServiceImpl extends ServiceImpl<CourseStuGroupMapper, CourseStuGroup> implements ICourseStuGroupService {

    private final ICourseStuGroupRelService courseStuGroupRelService;


    @Override
    public boolean add(CourseStuGroupReqDTO dto){
        this.checkByGroupName(dto.getGroupName(),null,dto.getCourseId());
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        // 拆分并去重、去空
        List<String> afterGroupNames = Arrays.stream(dto.getGroupName().split(","))
                .map(String::trim)
                .filter(StrUtil::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());

        // 2. 循环插入
        String nickname = AuthUtils.getNickname();
        int successCount = 0;
        for (String name : afterGroupNames) {
            CourseStuGroup bean = new CourseStuGroup();
            bean.setCourseId(dto.getCourseId());
            bean.setGroupName(name);   // 单个名称
            bean.setCustomerId(customerId);
            bean.setCreateBy(nickname);
            // 单条插入
            successCount += baseMapper.insert(bean);
        }
        return successCount == afterGroupNames.size();
    }

    @Override
    public CourseStuGroup selectGroupIdByUser(Long courseId, Long userId){
        return baseMapper.selectGroupIdByUser(courseId,userId);
    }
    @Override
    public boolean update(CourseStuGroupReqDTO dto){
        this.checkByGroupName(dto.getGroupName(),dto.getId(),dto.getCourseId());
        CourseStuGroup bean = baseMapper.selectById(dto.getId());
        if(ObjectUtil.isEmpty(bean)){
            throw new BizException("分组记录为空");
        }
        bean.setGroupName(dto.getGroupName());
        bean.setUpdateBy(AuthUtils.getNickname());
        int result = baseMapper.updateById(bean);
        boolean bool = result >0 ? true : false;
        return bool;
    }

    @Override
    public PageResult<GroupRespListDTO> pageList(GroupQueryDTO params){
        LambdaQueryWrapper<CourseStuGroup> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StrUtil.isNotBlank(params.getQ()), CourseStuGroup::getGroupName, params.getQ());
        queryWrapper.eq(CourseStuGroup::getCourseId,params.getCourseId());
        queryWrapper.eq(CourseStuGroup::getCustomerId,AuthUtils.getCurrentUser().getCustomerId());
        Page<CourseStuGroup> resultPage = baseMapper.selectPage(params.buildPage(), queryWrapper);

        PageResult<GroupRespListDTO> groupRespDTO = PageResult.of(resultPage, GroupRespListDTO.class);
        groupRespDTO.getList().forEach(x ->{
            x.setUserNum(courseStuGroupRelService.findCourseGroupStuNum(x.getId(),x.getCourseId()));
        });
        return groupRespDTO;
    }

    @Override
    public boolean deleteById(Long id){
        CourseStuGroup bean = this.getById(id);
        if(ObjectUtil.isEmpty(bean)){
            throw new BizException("分组记录为空");
        }
        int result = baseMapper.deleteById(bean);
        // 删除分组关系表
        LambdaQueryWrapper<CourseStuGroupRel> wrapper = Wrappers.<CourseStuGroupRel>lambdaQuery()
                .eq(CourseStuGroupRel::getGroupId, id);
        courseStuGroupRelService.remove(wrapper);
        boolean bool = result >0 ? true : false;
        return bool;
    }

    @Override
    public  String findGroupNameByUserId(Long courseId, Long userId){
        return baseMapper.selectGroupNameByUserId(courseId,userId);
    }

    private void checkByGroupName(String groupName,Long id,Long courseId) {
        if (StrUtil.isEmpty(groupName)) {
            throw new BizException("分组名称不能为空");
        }
        // 拆分并去重、去空
        List<String> names = Arrays.stream(groupName.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());

        if (names.isEmpty()) {
            throw new BizException("分组名称不能为空");
        }

        // 一次查询：只要有一个名称已存在就返回数量 > 0
        LambdaQueryWrapper<CourseStuGroup> wrapper = Wrappers.<CourseStuGroup>lambdaQuery()
                .eq(CourseStuGroup::getCourseId, courseId)
                .in(CourseStuGroup::getGroupName, names)
                .ne(id != null && id > 0, CourseStuGroup::getId, id) // 编辑时排除自己
                .eq(CourseStuGroup::getIsDeleted, 0);

        Long exist = baseMapper.selectCount(wrapper);
        if (exist > 0) {
            throw new BizException("分组名称已存在，请检查后重新输入");
        }
    }
}
